<?php
namespace src\logic;
use \classlib\core as C;
class ltoken {
	const CSed     = 'sed';
	/**
	 * 获取PC端生成的TOCKEN信息
	 * @param int $userid
	 * @param string $loginpw
	 * @param array $user
	 * @return string
	 */
	public static function pc($userid, $sid, $loginpw) {
		$user = sprintf('%d-%d-%d', $userid, $sid, C\config::$nowtime);
		$sign = $userid.'$'.\classlib\crypt\xxtea::encrypt($user, $loginpw);
		$sign = urlencode($sign);
		return $sign;
	}
	
	/**
	 * 验证签名的合法性
	 * @param string $sign
	 * @return bool
	 */
	public static function pccheck($sign) {
		list($userid, $sign) = explode('$', $sign);
		if (!is_numeric($userid) || $userid < 1) {
			return false;
		}
		$user = C\model::load('main.pl.userinfo')->set_dev($userid)->get_one($userid);
		$sign = \classlib\crypt\xxtea::decrypt($sign, $user['loginpw']);
		list($uid, $sid, $stime) = explode('-', $sign);
		if ($userid != $uid || !is_numeric($sid) || $sid < 1) {
			return false;
		}
		$user['studioid'] = $sid;
		return $user;
	}
	
	/**
	 * 获取web的随机跟踪码信息
	 * @return string
	 */
	public static function web() {
		$hash   = substr(md5(C\config::$nowtime), 0, 16);
		$data   = sprintf("%s-%d", $hash, C\config::$nowtime);
		$skey   = \classlib\crypt\xxtea::encrypt($data);
		return $skey;
	}
	
	/**
	 * 验证消息传递过程中的跟踪码
	 * @param string $skey
	 * @return bool
	 */
	public static function webcheck($skey='') {
		if (!$skey) {
			$skey  = \classlib\input::cookie(self::CSed);
		}
		if ($skey) {
			$data  = \classlib\crypt\xxtea::decrypt($skey);
			list($hash, $ltime) = explode('-', $data);
			if (strcmp($hash, substr(md5($ltime), 0, 16)) == 0) {
				return $hash;
			}
		}
		return false;
	}
	
	/**
	 * 设置随机种子签名资料信息
	 * @param string $ckey
	 * @param string $val
	 * @param number $expire
	 */
	public static function webcookie($ckey, $val, $expire=0) {
		setcookie($ckey, rawurldecode($val), $expire, '/');
	}
}